﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using System.Threading;

namespace XChipTool
{
    public partial class XChip_SCA_Area : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;

        private bool isRead = false;

        public event Action GetClick;

        public XChip_SCA_Area()
        {
            InitializeComponent();
        }

        private void XChip_SCA_Area_Load(object sender, EventArgs e)
        {
            zoomTrackBarControl1.Properties.Minimum = 0;
            zoomTrackBarControl1.Properties.Maximum = 60;

            zoomTrackBarControl2.Properties.Minimum = 0;
            zoomTrackBarControl2.Properties.Maximum = 255;

            scaTrackBar1.SendAlphaClick += ScaTrackBar1_SendAlphaClick;
            scaTrackBar1.SendTheatClick += ScaTrackBar1_SendTheatClick;
            ScaAreaShowHide(false);
            EnableSCA.Enabled = false;
        }

        private void ScaTrackBar1_SendTheatClick(int msg)
        {
            hue_center.Text = msg.ToString("X3");
            //低位
            var low = msg & 0xff;
            //高位
            var hig = (msg >> 8) & 0x01;
            var tempTag = Convert.ToUInt16(this.Tag);
            SetScaRegister($"ThetaTxt{tempTag * 2}", (ulong)hig);
            SetScaRegister($"ThetaTxt{tempTag * 2 + 1}", (ulong)low);
        }

        private void ScaTrackBar1_SendAlphaClick(int msg)
        {
            zoomTrackBarControl1.Value = msg;
            hue_width.Text = msg.ToString("X2");            
        }

        private void zoomTrackBarControl2_EditValueChanged(object sender, EventArgs e)
        {
            color_gain.Text = zoomTrackBarControl2.Value.ToString("X2");
            SetScaRegister($"GainTxt{this.Tag}", (ulong)zoomTrackBarControl2.Value);
        }

        private void zoomTrackBarControl1_EditValueChanged(object sender, EventArgs e)
        {
            hue_width.Text = zoomTrackBarControl1.Value.ToString("X2");
            SetScaRegister($"AlphaTxt{this.Tag}", (ulong)(zoomTrackBarControl1.Value & 0x3f));
            if (!string.IsNullOrEmpty(hue_center.Text)&&!string.IsNullOrEmpty(hue_width.Text))
            {
                int thetaNum = Convert.ToInt32(hue_center.Text, 16);
                if (Convert.ToUInt32(hue_width.Text, 16) > 0x3c) {                   
                    scaTrackBar1.SetScrollBarValue(thetaNum, 0x3c);
                }
                else { int alphaNum = Convert.ToInt32(hue_width.Text, 16);
                    scaTrackBar1.SetScrollBarValue(thetaNum, alphaNum);
                }   
            }           
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            WaitBefore.Start("读取中", "正在加载中", 10);
            isRead = true;
            long nCenter1, nCenter2, nWidth, nGain, nArea;

            nArea = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "EnableSCA0").First().Address, 16), sPortTemp);
            //nArea = SerialSend.ReadRegister((0x80303b00 | 0x00e), sPortTemp);

            switch (this.Tag.ToString())
            {
                case "0":
                    {
                        long temp = (nArea >> 0) & 1;
                        if (temp == 0)
                        {
                            EnableSCA.CheckState = CheckState.Unchecked;
                            ScaAreaShowHide(false);
                        }
                        else {
                            EnableSCA.CheckState = CheckState.Checked;
                            ScaAreaShowHide(true);
                            //nCenter1 = SerialSend.ReadRegister((0x80303b00 | 0x000), sPortTemp);
                            //nCenter2 = SerialSend.ReadRegister((0x80303b00 | 0x001), sPortTemp);
                            //alpha
                            nWidth = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "AlphaTxt0").First().Address, 16), sPortTemp);
                            //nWidth = SerialSend.ReadRegister((0x80303b00 | 0x002), sPortTemp);
                            //gain
                            nGain = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "GainTxt0").First().Address, 16), sPortTemp);
                            //nGain = SerialSend.ReadRegister((0x80303b00 | 0x003), sPortTemp);
                            //theta
                            nCenter1 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt0").First().Address, 16), sPortTemp);
                            nCenter2 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt1").First().Address, 16), sPortTemp);
                            long tempc = ((nCenter1 << 8) & 0x100) | (nCenter2);

                            hue_center.Text = tempc.ToString("X3");
                            hue_width.Text = nWidth.ToString("X2");
                            zoomTrackBarControl1.Value = (int)nWidth;
                            color_gain.Text = nGain.ToString("X2");
                            zoomTrackBarControl2.Value = (int)nGain;
                        }
                    }
                    break;
                case "1":
                    {
                        long temp = (nArea >> 1) & 1;
                        if (temp == 0)
                        {
                            EnableSCA.CheckState = CheckState.Unchecked;
                            ScaAreaShowHide(false);
                        }
                        else
                        {
                            EnableSCA.CheckState = CheckState.Checked;
                            ScaAreaShowHide(true);
                            //nCenter1 = SerialSend.ReadRegister((0x80303b00 | 0x004), sPortTemp);
                            //nCenter2 = SerialSend.ReadRegister((0x80303b00 | 0x005), sPortTemp);
                            //alpha
                            nWidth = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "AlphaTxt1").First().Address, 16), sPortTemp);
                            //nWidth = SerialSend.ReadRegister((0x80303b00 | 0x006), sPortTemp);
                            //gain
                            nGain = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "GainTxt1").First().Address, 16), sPortTemp);
                            //nGain = SerialSend.ReadRegister((0x80303b00 | 0x007), sPortTemp);
                            //theta
                            nCenter1 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt2").First().Address, 16), sPortTemp);
                            nCenter2 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt3").First().Address, 16), sPortTemp);
                            long tempc = ((nCenter1 << 8) & 0x100) | (nCenter2);

                            hue_center.Text = tempc.ToString("X3");
                            hue_width.Text = nWidth.ToString("X2");
                            zoomTrackBarControl1.Value = (int)nWidth;
                            color_gain.Text = nGain.ToString("X2");
                            zoomTrackBarControl2.Value = (int)nGain;
                        }
                    }
                    break;
                case "2":
                    {
                        long temp = (nArea >> 2) & 1;
                        if (temp == 0)
                        {
                            EnableSCA.CheckState = CheckState.Unchecked;
                            ScaAreaShowHide(false);
                        }
                        else
                        {
                            EnableSCA.CheckState = CheckState.Checked;
                            ScaAreaShowHide(true);
                            //nCenter1 = SerialSend.ReadRegister((0x80303b00 | 0x008), sPortTemp);
                            //nCenter2 = SerialSend.ReadRegister((0x80303b00 | 0x009), sPortTemp);
                            //alpha
                            nWidth = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "AlphaTxt2").First().Address, 16), sPortTemp);
                            //nWidth = SerialSend.ReadRegister((0x80303b00 | 0x00a), sPortTemp);
                            //gain
                            nGain = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "GainTxt2").First().Address, 16), sPortTemp);
                            //nGain = SerialSend.ReadRegister((0x80303b00 | 0x00b), sPortTemp);
                            //theta
                            nCenter1 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt4").First().Address, 16), sPortTemp);
                            nCenter2 = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "ThetaTxt5").First().Address, 16), sPortTemp);
                            long tempc = ((nCenter1 << 8) & 0x100) | (nCenter2);

                            hue_center.Text = tempc.ToString("X3");
                            hue_width.Text = nWidth.ToString("X2");
                            zoomTrackBarControl1.Value = (int)nWidth;
                            color_gain.Text = nGain.ToString("X2");
                            zoomTrackBarControl2.Value = (int)nGain;
                        }
                    }
                    break;
                default:
                    break;
            }
            EnableSCA.Enabled = true;
            GetClick?.Invoke();

            isRead = false;
            WaitBefore.Close();
        }

       
        private void ScaAreaShowHide(bool isbool) {
            zoomTrackBarControl1.Enabled = isbool;
            zoomTrackBarControl2.Enabled = isbool;
            hue_center.Enabled = isbool;
            hue_width.Enabled = isbool;
            color_gain.Enabled = isbool;
            scaTrackBar1.ScaEnableToBool(isbool);
            
        }

        private void EnableSCA_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var  nArea = SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == "EnableSCA0").First().Address, 16), sPortTemp);
            switch (this.Tag.ToString())
            {
                case "0":
                    {
                        if (EnableSCA.CheckState == CheckState.Checked)
                        {
                            SetScaRegister("EnableSCA0",(ulong)(nArea|0x1));
                        }
                        else {
                            SetScaRegister("EnableSCA0", (ulong)(nArea & 0xfe));
                        }
                    }
                    break;
                case "1": {
                        if (EnableSCA.CheckState == CheckState.Checked)
                        {
                            SetScaRegister("EnableSCA0", (ulong)(nArea | 0x02));
                        }
                        else
                        {
                            SetScaRegister("EnableSCA0", (ulong)(nArea & 0xfd));
                        }
                    } break;
                case "2": {
                        if (EnableSCA.CheckState == CheckState.Checked)
                        {
                            SetScaRegister("EnableSCA0", (ulong)(nArea | 0x04));
                        }
                        else
                        {
                            SetScaRegister("EnableSCA0", (ulong)(nArea & 0xfb));
                        }
                    } break;
                default:
                    break;
            }
            if (EnableSCA.CheckState == CheckState.Checked)
            {
                ScaAreaShowHide(true);
            }
            else
            {
                ScaAreaShowHide(false);
            }
        }


        private void SetScaRegister(string nameType, ulong add)
        {           
            if (!sPortTemp.IsOpen)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            if (isRead) return;
            if (XChipHelp.XChipSca.Where(c => c.NameType == nameType).Count() > 0)
            {
                SerialSend.WriteRegister(Convert.ToUInt32(XChipHelp.XChipSca.Where(c => c.NameType == nameType).First().Address, 16), add, sPortTemp);
            }
        }

        private void ThetaTxt_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var txtNum = Convert.ToUInt32(txtEdit.Text, 16);
            if (txtNum > 0x168)
            {
                txtNum = 0x168;

            }
            switch (this.Tag.ToString())
            {
                case "0":
                    {

                        //低位
                        var low = txtNum & 0xff;
                        //高位
                        var hig = (txtNum >> 8) & 0x01;

                        SetScaRegister("ThetaTxt0", (ulong)hig);
                        SetScaRegister("ThetaTxt1", (ulong)low);
                    }
                    break;
                case "1":
                    {
                        //低位
                        var low = txtNum & 0xff;
                        //高位
                        var hig = (txtNum >> 8) & 0x01;

                        SetScaRegister("ThetaTxt2", (ulong)hig);
                        SetScaRegister("ThetaTxt3", (ulong)low);
                    }
                    break;
                case "2":
                    {
                        //低位
                        var low = txtNum & 0xff;
                        //高位
                        var hig = (txtNum >> 8) & 0x01;

                        SetScaRegister("ThetaTxt4", (ulong)hig);
                        SetScaRegister("ThetaTxt5", (ulong)low);
                    }
                    break;
                default:
                    break;
            }
            if (Convert.ToUInt32(txtEdit.Text, 16) > 0x168)
            {
                hue_center.Text = "168";
            }
            scaTrackBar1.SetScrollBarValue(Convert.ToInt32(txtEdit.Text, 16), Convert.ToInt32(hue_width.Text, 16));

        }

        private void AlphaTxt_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var txtNum = Convert.ToUInt32(txtEdit.Text, 16);
            if (txtNum > 0x3c)
            {
                txtNum = 0x3c;

            }
            switch (this.Tag.ToString())
            {
                case "0": SetScaRegister("AlphaTxt0", (ulong)(txtNum & 0x3f)); break;
                case "1": SetScaRegister("AlphaTxt1", (ulong)(txtNum & 0x3f)); break;
                case "2": SetScaRegister("AlphaTxt2", (ulong)(txtNum & 0x3f)); break;
                default:
                    break;
            }
            if (Convert.ToUInt32(txtEdit.Text, 16) > 0x3c)
            {
                zoomTrackBarControl1.Value = 0x3c;
                isRead = true;
                hue_width.Text = "3c";
                isRead = false;
            }
            else
            {
                zoomTrackBarControl1.Value = Convert.ToInt32(txtEdit.Text, 16);
            }
        }

        private void GainTxt_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            var txtNum = Convert.ToUInt32(txtEdit.Text, 16);
            if (txtNum > 0xff)
            {
                txtNum = 0xff;

            }
            switch (this.Tag.ToString())
            {
                case "0": SetScaRegister("GainTxt0", (ulong)(txtNum & 0xff)); break;
                case "1": SetScaRegister("GainTxt1", (ulong)(txtNum & 0xff)); break;
                case "2": SetScaRegister("GainTxt2", (ulong)(txtNum & 0xff)); break;
                default:
                    break;
            }
            if (Convert.ToUInt32(txtEdit.Text, 16) > 0xff)
            {
                hue_width.Text = "ff";
            }
            zoomTrackBarControl2.Value = Convert.ToInt32(txtEdit.Text, 16);
        }

        private void ThetaTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ThetaTxt_Leave(sender, null);
            }
        }

        private void AlphaTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AlphaTxt_Leave(sender, null);
            }
        }

        private void GainTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GainTxt_Leave(sender, null);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       选择待调色调段（Area0、Area1、Area2）后，可分别使能并进行中心色调、色调半径、颜色增益的调整，其中颜色增益调整时 0x40 为基准倍数，value＞0x40 则颜色增强，value＜0x40 则颜色减弱。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            string str = "       选择待调色调段（Area0、Area1、Area2）后，可分别使能并进行中心色调、色调半径、颜色增益的调整，其中颜色增益调整时 0x40 为基准倍数，value＞0x40 则颜色增强，value＜0x40 则颜色减弱。\r\n       更多详见《调试工具用户手册》。";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("SCA调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }
    }
}
